const express = require("express");
const bodyParser = require("body-parser");
const fs = require("fs");

const app = express();
app.use(express.static("www"));

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(3000, () => {
    console.log("http:/localhost:3000");
})
app.post("/zhuce", (req, res) => {
    console.log(req.body);
    var data = fs.readFileSync("./users.txt");
    // console.log("data",data.toString);
    if (data.toString()) {

        var arr = data.toString().split("$");
        var arr1 = arr.map((item) => JSON.parse(item));

        console.log("---", arr1);
        var isShow = true;
        for (let i = 0; i < arr1.length; i++) {
            if (req.body.username == arr1[i].username) {
                isShow = false;
            }

        }
        if (isShow) {
            var str = "$" + JSON.stringify(req.body);
            fs.appendFile("./users.txt", str, function (err) {
                if (!err) {
                    // console.log("添加成功")
                    res.json({ success: 1, data: "添加成功" })
                }
            })
        } else {
            // console.log("当前用户已存在");
            res.json({ success: 0, data: "当前用户已存在" })
        }


    } else {
        // console.log("没有值");
        var str = JSON.stringify(req.body);
        fs.appendFile("./users.txt", str, function (err) {
            if (!err) {
                // console.log("添加成功");
                res.json({ success: 1, data: "添加成功" })
            }
        })
    }
})





app.post("/login", function (req, res) {
    console.log("登录接收到的数据");
    console.log(req.body);
    //判断当前用户是否存在
    // 用户存在再判断密码是否正确

    // 读取users.txt文件
    var data = fs.readFileSync("./users.txt");
    console.log("获取的data的值");
    // console.log(data);
    // 获取的txt文件的内容  是整个字符串
    console.log(data.toString());

    var arr = data.toString().split("$");
    console.log("arr的值是一个数组包含了很多字符串");
    console.log(arr);

    var arr1 = arr.map((item) => JSON.parse(item));
    //得到的数据内包裹了多个对象
    console.log(arr1);

    //假设当前用户不存在
    var isShow = false, pass = null;
    for (let i = 0; i < arr1.length; i++) {
        if (req.body.username == arr1[i].username) {

            isShow = true;
            pass = arr1[i].password;
        }

    }
    if (isShow) {
        if (req.body.password == pass) {
            res.json({ success: 1, data: "登录成功"})
        }else{
            res.json({ success: 0, data: "密码错误"})
        }
    }else{
        //当前用户不存在
        res.json({ success: 0, data: "当前用户不存在"})
    }
})